package com.zzyl.service.impl;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @param
 * @return
 */
@Service
public class WeChatServiceImpl implements WeChatService {
    private final String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    private final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    private final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appid}")
    private String APP_ID;
    @Value("${zzyl.wechat.appsecret}")
    private String APP_SECRET;

    //获取openID
    @Override
    public String getOpenid(String code) {
        Map map = getMapInfo();
        map.put("js_code", code);
        HttpResponse execute = HttpUtil.createRequest(Method.GET, OPEN_ID_URL).form(map).execute();
        String body = execute.body();
        JSONObject json = JSONUtil.parseObj(body);
        if (json.getInt("errcode") != null) {
            throw new RuntimeException(json.getStr("errmsg"));
        }
        String openid = json.getStr("openid");
        return openid;
    }

    //获取phoneNumber
    @Override
    public String getPhone(String phoneCode) {
        String accessToken = getAccessToken();
        Map map = new HashMap();
        map.put("code", phoneCode);
        String result = HttpUtil.post(PHONE_URL + accessToken, JSONUtil.toJsonStr(map));
        JSONObject json = JSONUtil.parseObj(result);
        if (json.getInt("errcode") != 0) {
            throw new RuntimeException(json.getStr("errmsg"));
        }
        String phoneInfo = json.getStr("phone_info");
        JSONObject entries = JSONUtil.parseObj(phoneInfo);
        String phoneNumber = entries.getStr("phoneNumber");
        return phoneNumber;
    }

    private String getAccessToken() {
        Map map = getMapInfo();
        HttpResponse execute = HttpUtil.createRequest(Method.GET, ACCESS_TOKEN_URL).form(map).execute();
        String body = execute.body();
        JSONObject json = JSONUtil.parseObj(body);
        if (json.getInt("errcode") != null) {
            throw new RuntimeException(json.getStr("errmsg"));
        }
        String accessToken = json.getStr("access_token");
        return accessToken;
    }

    private Map getMapInfo() {
        Map map = new HashMap();
        map.put("appid", APP_ID);
        map.put("secret", APP_SECRET);
        return map;
    }
}
